package com.clc.comm.security;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.security.web.util.AntPathRequestMatcher;
import org.springframework.security.web.util.RequestMatcher;

import com.clc.comm.util.XStreamUtil;
import com.clc.test.XStreamTest;


//1 加载资源与权限的对应关系
public class MySecurityMetadataSource implements FilterInvocationSecurityMetadataSource {
	static Log log = LogFactory.getLog(MySecurityMetadataSource.class.getName());
	//由spring调用
	public MySecurityMetadataSource() {
		
		loadResourceDefine();
	}

	private static Map<String, Collection<ConfigAttribute>> resourceMap = null;


	public Collection<ConfigAttribute> getAllConfigAttributes() {
		// TODO Auto-generated method stub
		return null;
	}

	public boolean supports(Class<?> clazz) {
		// TODO Auto-generated method stub
		return true;
	}
	//加载所有资源与权限的关系
	private void loadResourceDefine() {
		if(resourceMap == null) {
			InputStream in = null;
			try {
				resourceMap = new HashMap<String, Collection<ConfigAttribute>>();
				in = (this.getClass().getClassLoader().getResourceAsStream("securitytResources.xml"));
				Map<String, Class> map= new HashMap<String, Class>();
				map.put("roles", List.class);
				List<Resources> resList =  (List<Resources>) XStreamUtil.parseXML(in, Resources.class,map);
				for (Resources res:resList) {
					Collection<ConfigAttribute> role = new ArrayList<ConfigAttribute>();
					ConfigAttribute configAttribute = new SecurityConfig(res.getRoleName());
					role.add(configAttribute);
					for (String url : res.getUrls()) {
						resourceMap.put(url, role);
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
				throw new AccessDeniedException("系统异常");
			}
			
		}
/*		
		Set<Entry<String, Collection<ConfigAttribute>>> resourceSet = resourceMap.entrySet();
		Iterator<Entry<String, Collection<ConfigAttribute>>> iterator = resourceSet.iterator();*/
	}
	//返回所请求资源所需要的权限
	public Collection<ConfigAttribute> getAttributes(Object object) throws IllegalArgumentException {
		if(resourceMap == null || resourceMap.size()==0) {
			loadResourceDefine();
		}
		SecurityContext seContext = SecurityContextHolder.getContext();
		FilterInvocation invocation = (FilterInvocation) object;
		String requestUrl = invocation.getRequestUrl();
		int firstQuestionMarkIndex = requestUrl.indexOf("?");
        if (firstQuestionMarkIndex != -1) {
        	requestUrl = requestUrl.substring(0, firstQuestionMarkIndex);
        }
        Iterator<String> ite = resourceMap.keySet().iterator();//得到资源
		Authentication auth = seContext.getAuthentication();
		Object obj = auth.getPrincipal();
		log.info("requestUrl is " + requestUrl);
		if(obj instanceof UserDetails){
			UserDetails user  = (UserDetails)obj;
			log.info("登录人: " + user.getUsername());
			Iterator<GrantedAuthority> cad = (Iterator<GrantedAuthority>) user.getAuthorities().iterator();
			while (cad.hasNext()) {
				log.info("登录人的GrantedAuthority: " + cad.next().getAuthority());
			}
			while (ite.hasNext()) {
				String resURL = ite.next();
				RequestMatcher urlMatcher = new AntPathRequestMatcher(resURL);
				if (urlMatcher.matches(invocation.getHttpRequest())) {
					return resourceMap.get(resURL);
				}
			}
		}else{
			log.info("未登录");
			try {
				invocation.getHttpResponse().sendRedirect("/myzqon/login.jsp");
			} catch (IOException e) {
				e.printStackTrace();
			}
			return null;
		}
		return null;
	}

}
